import { LogContextImpl } from '../impl/LogContextImpl'
import { LoggerImpl } from '../impl/LoggerImpl'
import { LogContext } from './LogContext'
import { Logger } from './Logger'
import { LoggerConfig } from './LoggerConfig'
import { LoggerLevel } from './LoggerLevel'

/**
 * LoggerFactory
 *
 * @author LL
 * @date 2022-01-19 下午 03:28
 **/
export class LoggerFactory {
    private readonly config: LoggerConfig
    private readonly context: LogContext
    /**
     * 缓存
     */
    private readonly loggerCache: Map<string, Logger> = new Map<string, Logger>()

    public constructor(config: LoggerConfig) {
        this.config = config
        this.context = new LogContextImpl(this.config)
    }

    // noinspection JSUnusedGlobalSymbols
    /**
     * 获取一个日志记录器, 记录器会被按 {@code name} 缓存
     * @param {string} name 记录器名称
     * @param {LoggerLevel} debugLevel 调试用输出等级, 覆盖全局配置
     * @return {Logger}
     */
    public getLogger = (name: string, debugLevel?: LoggerLevel): Logger => {
        const cache = this.loggerCache.get(name)
        if (cache) {
            return cache
        }

        const impl = new LoggerImpl(name, this.context, debugLevel)
        this.loggerCache.set(name, impl)

        return impl
    }
}
